package org.homeworkteam.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/video")
public class VideoController {

    private static final String UPLOAD_DIR = "D:\\vedio";

    /**
     * 根据文件名返回视频文件
     *
     * @param url 视频文件名
     * @return 视频文件或者错误信息
     */
    @GetMapping("/get")
    public ResponseEntity<?> getVideo(@RequestParam("url") String url) {
        // 拼接文件路径
        File videoFile = new File(UPLOAD_DIR, url);

        // 检查文件是否存在
        if (videoFile.exists() && videoFile.isFile()) {
            try {
                // 返回视频文件的资源
                Resource resource = new UrlResource(videoFile.toURI());

                // 设置 HTTP 头信息
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_TYPE, "video/mp4"); // 设置视频类型
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + url + "\"");

                return ResponseEntity.ok()
                        .headers(headers)
                        .body(resource);

            } catch (IOException e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body("文件读取错误: " + e.getMessage());
            }
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("文件不存在");
        }
    }


}
